/*
 * @Author: mikey.zhaopeng 
 * @Date: 2018-11-27 23:46:59 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2018-12-01 21:57:39
 */
import 'package:flutter/material.dart';
import '../constants.dart' show Constants, AppColors, AppStyles;
import '../modal/contacts.dart' show Contact, ContantsPageData;

const List<String> INDEX_BAR_WORDS = [
  "↑",
  "☆",
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z"
];

class ContactPage extends StatefulWidget {
  Color _indexBarBg = Colors.transparent;
  String _currentLetter = '';
  @override
  _ContactPageState createState() => new _ContactPageState();
}

class _ContactPageState extends State<ContactPage> {
  ScrollController _scrollController;
  final ContantsPageData data = ContantsPageData.mock();
  final List<Contact> _contacts = [];
  final Map _letterPositionMap = {INDEX_BAR_WORDS[0]: 0.0};

  final List<_ContactItem> _functionButtons = [
    _ContactItem(
        avatar: "assets/images/ic_new_friend.png",
        title: "新的朋友",
        onpressed: () => print("添加朋友")),
    _ContactItem(
        avatar: "assets/images/ic_group_chat.png",
        title: "群聊",
        onpressed: () => print("群聊")),
    _ContactItem(
        avatar: "assets/images/ic_tag.png",
        title: "标签",
        onpressed: () => print("标签")),
    _ContactItem(
        avatar: "assets/images/ic_public_account.png",
        title: "公众号",
        onpressed: () => print("公众号"))
  ];

  @override
  void initState() {
    super.initState();
    _contacts
      ..addAll(data.contacts)
      ..addAll(data.contacts)
      ..addAll(data.contacts)
      ..sort((Contact a, Contact b) => a.nameIndex.compareTo(b.nameIndex));
    _scrollController = new ScrollController();

    //计算每个section滚动的位置
    double totalPos = _functionButtons.length * _ContactItem.height(false);
    for (int i = 0; i < _contacts.length; i++) {
      bool hasGroupTitle = true;
      if (i > 0 && _contacts[i].nameIndex == _contacts[i - 1].nameIndex) {
        hasGroupTitle = false;
      }
      if (hasGroupTitle) {
        _letterPositionMap[_contacts[i].nameIndex] = totalPos;
      }
      totalPos = totalPos + _ContactItem.height(hasGroupTitle);
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  String getLetter(BuildContext context,Offset globalPos,double tailTitle){
    RenderBox _box = context.findRenderObject();
    var local = _box.globalToLocal(globalPos);
    int index = (local.dy ~/ tailTitle).clamp(0, INDEX_BAR_WORDS.length -1);
    return INDEX_BAR_WORDS[index];
  }

  void  _jumpIndex(String letter){
    if(_letterPositionMap.isNotEmpty){
      final _pos = _letterPositionMap[letter];
      if(_pos != null){
         _scrollController.animateTo(_pos,
            duration: Duration(milliseconds: 200), curve: Curves.ease);
      }
    }
  }

  Widget _buildIndexBar(BuildContext context, BoxConstraints constraints) {
    final double _totalHeight = constraints.biggest.height;
    final double tailHeight = _totalHeight /INDEX_BAR_WORDS.length;
    final List<Widget> _letters = INDEX_BAR_WORDS.map((String word) {
      return Expanded(
        child: Text(word),
      );
    }).toList();
    return GestureDetector(
      onVerticalDragDown: (DragDownDetails details) {
        setState(() {
          widget._indexBarBg = Colors.black26;
          widget._currentLetter = getLetter(context, details.globalPosition,tailHeight);
        });
        _jumpIndex(widget._currentLetter );
      },
      onVerticalDragEnd: (DragDownDetails) {
        setState(() {
          widget._indexBarBg = Colors.transparent;
          widget._currentLetter = '';
        });
      },
      onVerticalDragUpdate: (DragUpdateDetails details){
         setState(() {
          widget._indexBarBg = Colors.black26;
          widget._currentLetter = getLetter(context, details.globalPosition,tailHeight);
        });
        _jumpIndex(widget._currentLetter );
      },
      onVerticalDragCancel: () {
        setState(() {
          widget._indexBarBg = Colors.transparent;
          widget._currentLetter = '';
        });
      },
      child: Column(
        children: _letters,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> _body =[
        ListView.builder(
          controller: _scrollController,
          itemCount: _functionButtons.length + _contacts.length,
          itemBuilder: (BuildContext context, int index) {
            if (index < _functionButtons.length) {
              // totalPos += _functionButtons[index].height(false);
              return _functionButtons[index];
            } else {
              int _contactIndex = index - _functionButtons.length;
              bool _isGroupTitle = true;
              Contact _contact = _contacts[_contactIndex];
              //当前的下标和上一个下标是否一致，如果一致则没有表头
              if (_contactIndex >= 1 &&
                  _contact.nameIndex ==
                      _contacts[_contactIndex - 1].nameIndex) {
                _isGroupTitle = false;
              }
              final _ContactItem _contactItem = _ContactItem(
                avatar: _contact.avatar,
                title: _contact.name,
                groupTitle: _isGroupTitle ? _contact.nameIndex : null,
              );
              return _contactItem;
            }
          },
        ),
        Positioned(
          top: 0.0,
          right: 0.0,
          bottom: 0.0,
          width: Constants.IndexBarWidth,
          child: Container(
            color: widget._indexBarBg,
            child: LayoutBuilder(
              builder:_buildIndexBar ,
            ),
          ),
        ),
    ];
    if(widget._currentLetter.isNotEmpty){
      _body.add(
        Center(
          child: Container(
            decoration: BoxDecoration(
              color: AppColors.IndexLetterBoxBg,
              borderRadius: BorderRadius.all(Radius.circular(Constants.IndexLettersBoxRadius))
            ),
            width: Constants.IndexLetterBoxSize,
            height: Constants.IndexLetterBoxSize,
            child: Center(
              child: Text(widget._currentLetter,style: AppStyles.IndexLettersTextStyle,),
            ),
          ),
        ),
      );
    }
    return Stack(
      children: _body,
    );
  }
}

class _ContactItem extends StatelessWidget {
  _ContactItem(
      {@required this.avatar,
      @required this.title,
      this.groupTitle,
      this.onpressed});

  final String avatar;
  final String title;
  final String groupTitle;
  final VoidCallback onpressed;

  static const double PADDING_VERTICAL = 10.0;
  static const double GROUP_TITLE_HEIGHT = 24.0;

  bool get _isAvatarFromNet {
    return this.avatar.startsWith('http') || this.avatar.startsWith('https');
  }

  static double height(bool hasGroupTitle) {
    final _buttonHeight = PADDING_VERTICAL * 2 +
        Constants.ContactAvatarSize +
        Constants.DividerWidth;
    if (hasGroupTitle) {
      return _buttonHeight + GROUP_TITLE_HEIGHT;
    }
    return _buttonHeight;
  }

  @override
  Widget build(BuildContext context) {
    //左边的图标
    Widget avatarIcon;
    if (_isAvatarFromNet) {
      avatarIcon = Image.network(
        avatar,
        width: Constants.ContactAvatarSize,
        height: Constants.ContactAvatarSize,
      );
    } else {
      avatarIcon = Image.asset(
        avatar,
        width: Constants.ContactAvatarSize,
        height: Constants.ContactAvatarSize,
      );
    }
    //列表项主题部分
    Widget _button = Container(
      margin: const EdgeInsets.symmetric(horizontal: 16.0),
      padding: const EdgeInsets.symmetric(vertical: PADDING_VERTICAL),
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(
                  color: Color(AppColors.DividerColor),
                  width: Constants.DividerWidth))),
      child: Row(
        children: <Widget>[avatarIcon, SizedBox(width: 10.0), Text(title)],
      ),
    );
    //分组标签
    Widget _itemBody;
    if (this.groupTitle != null) {
      _itemBody = Column(
        children: <Widget>[
          Container(
            height: GROUP_TITLE_HEIGHT,
            padding: const EdgeInsets.only(left: 16.0),
            color: const Color(AppColors.ContactGroupTitleBg),
            alignment: Alignment.centerLeft,
            child: Text(
              this.groupTitle,
              style: AppStyles.GroupTitleItemTextStyle,
            ),
          ),
          _button,
        ],
      );
    } else {
      _itemBody = _button;
    }

    return Container(
      child: _itemBody,
    );
  }
}
